package controllers

import (
	"AndroidBlog/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
)

type ArticleController struct {
	beego.Controller
}

const (
	key = 123
)

func (c *ArticleController) Post() {
	c.Get()
}

func (c *ArticleController) Get() {
	method := c.Ctx.Input.Param(":path")
	k, _ := c.GetInt("k")
	fmt.Println("key-> ", k, " and ", method)
	if k == key {
		if "wanandroid" == method {
			page, e := c.GetInt("page")
			if e != nil {
				page = 1
			}
			wstr := doCrawlWanandroid(page)
			c.Ctx.WriteString(wstr)
		} else if "csdn" == method {
			c.Ctx.WriteString("hello csdn")
		} else {
			c.Ctx.WriteString("need source")
		}
		return
	}
	page, _ := c.GetInt("page")
	fmt.Println("page=> ", page)
	re := getArticle(page)
	c.Ctx.WriteString("hello,android blog \r\n " + re)
}

func getArticle(page int) (string) {
	var arr []models.Article
	var count int64
	if page > 0 {
		arr, count = models.ArticleGet(page, 20)
	}
	fmt.Println("getresult: ", page, " ", arr, " c ", count)
	resp := ArtResp{}
	if arr == nil {
		resp.ErrCode = -1
		resp.ErrMsg = "异常"
	} else {
		resp.ErrCode = 0
		resp.ErrMsg = ""
		list := ArtListData{}
		list.Count = count
		list.List = arr
		resp.Data = list
	}
	bytes, e := json.Marshal(&resp)
	re := string(bytes)
	fmt.Println(re,"err-> ",e)
	return re
}

//--------------------定义输出对象 start-------------------------------------

type ArtResp struct {
	ErrCode int         `json:"errCode"`
	ErrMsg  string      `json:"errMsg"`
	Data    ArtListData `json:"data,omitempty"`
}

type ArtListData struct {
	Count int64            `json:"count,omitempty"`
	List  []models.Article `json:"list,omitempty"`
}

//--------------------定义输出对象 end-------------------------------------
